<script setup>
import axios from "axios";
import { message } from "ant-design-vue";
import { useUserStore } from "@stores/counter.js";
import TestForm from "@components/Test/TestForm.vue";

const testForm = ref();//初始化表单组件
const selectedId = ref( 0 );
const addForm = ref( false );
const formLoading = ref(false); // 父组件控制 loading 状态
const handleSubmit = async ( formData ) => {
  formLoading.value = true; // 开始提交时设置 loading
  try {
    const requestUrl = ( formData.id ) ? '/api/tags-edit' : '/api/tags-create';
    const res = await axios.get( requestUrl,  {
      id : formData.id ?? '',
      title :formData.activity_name,
      sort :formData.resource,
      state :(!!formData.activity_type),
    });
    if ( res.data.code === 200 ) {
      message.success( res.data.msg , 2, () => {
        addForm.value = false;
        testForm.value.reset();
      });
    } else {
      message.error( res.data.msg );
    }
  } catch ( error ) {console.log( error );
  } finally { formLoading.value = false;}
}

const userStore = useUserStore();
const columns = [
  {
    key : 'id',
    title : 'id',
    dataIndex : 'id',
  },
  {
    key : 'title',
    title : '标签名',
    dataIndex : 'title',
  },
  {
    key : 'state',
    title : '状态',
    dataIndex : 'state',
  },
  {
    key : 'sort',
    title : '排序',
    dataIndex : 'sort',
  },
  {
    key : 'create_time',
    title : '添加时间',
    dataIndex : 'create_time',
  },
  {
    key : 'action',
    title : '操作',
    dataIndex : 'action',
  },
];
const data = ref( [] );
const getList = () => {
  axios.get( '/api/tags-list' ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      data.value = res.data.data.list.map( item => ({
        ...item,
        key : item.id
      }) );
    }
  } ).catch( err => {
    console.log( err );
  } )
}

const state = reactive( {
  selectedRowKeys : [],
  loading : false,
} );
const hasSelected = computed( () => state.selectedRowKeys.length > 0 );
const edit = () => {
  state.loading = true;
  setTimeout( () => {
    state.selectedRowKeys = [];
    state.loading = false;
  }, 1000 );
};
const onSelectChange = ( selectedRowKeys ) => {
  state.selectedRowKeys = selectedRowKeys;
};
const changeState = ( id, state ) => {
  console.log( id, state );
}

const add = () => {
  selectedId.value = 0;
  addForm.value = true
}

/**
 * 修改数据
 * @param {number} id
 */
const modify = ( id ) => {
  addForm.value = true
  selectedId.value = id;
}

/**
 * 删除数据
 * @param {number} id
 */
const handleDelete = ( id ) => {
  console.log( id );
}

const input = useTemplateRef('inputRef');

watchEffect(() => {
  if ( input.value ) {
    input.value.focus();
  }
});

// 初始化数据
onMounted( () => {
  input.value.focus();
  getList();
} );
</script>

<template>
  <div>
    <a-space class="mt-2 mb-2">
      <a-input ref="inputRef" placeholder="请输入搜索内容" allow-clear></a-input>
      <a-button type="primary" :disabled="!hasSelected" :loading="state.loading" @click="edit">编辑</a-button>
      <a-button @click="userStore.setName()">{{ userStore.name }}</a-button>
      <a-button @click="userStore.resetName()">重置</a-button>
      <a-button @click="add">添加数据</a-button>
      
      <a-modal v-model:open="addForm" width="800px" title="添加数据" :footer="null">
        <TestForm ref="testForm" @submit="handleSubmit" :id="selectedId" :loading="formLoading" />
      </a-modal>
    </a-space>
    <div>
      <a-table :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }" :columns="columns" :data-source="data">
        <template #bodyCell="{column, text, record}">
          <template v-if="column.key === 'state'">
            <a-switch v-model:checked="record.state" checked-children="开启" un-checked-children="关闭" @change="changeState(record.id, record.state)"/>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="primary" @click="modify(record.id)">编辑</a-button>
              <a-popconfirm title="确认删除吗?" @confirm="handleDelete(record.id)" ok-text="确认" cancel-text="取消">
                <a-button type="primary" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<!--全局样式-->
<style>
@import "tailwindcss";

</style>
<!--当前组件样式表-->
<style scoped>


</style>